package com.example.curator.leader;

import com.example.curator.CuratorClientUtils;
import com.google.common.collect.Lists;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.CloseableUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 官方demo
 */
public class LeaderSelectorDemo {
    private static final int CLIENT_QTY = 10;

    private static final String PATH = "/examples/leader";

    public static void main(String[] args) throws Exception {

        List<CuratorFramework> clients = Lists.newArrayList();
        List<LeaderClient> leaders = Lists.newArrayList();
        try {
            for (int i = 0; i < CLIENT_QTY; ++i) {
                CuratorFramework client = CuratorClientUtils.getInstance();
                clients.add(client);

                LeaderClient leaderClient = new LeaderClient(client, PATH, "Client #" + i);
                leaders.add(leaderClient);

                leaderClient.start();
            }

            System.out.println("Press enter/return to quit\n");
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } finally {
            System.out.println("Shutting down...");
            for (LeaderClient leaderClient : leaders) {
                CloseableUtils.closeQuietly(leaderClient);
            }
            for (CuratorFramework client : clients) {
                CloseableUtils.closeQuietly(client);
            }

        }
    }
}